# -*- coding: utf-8 -*-
from odoo import models, fields, api
from datetime import datetime
import time
import json
import xmltodict
import urllib
import urllib2
import requests
from odoo import http, exceptions
from odoo.http import request

import logging

_logger = logging.getLogger(__name__)


class Delivery(http.Controller):
    @http.route('/salesys/delivery',auth='public', methods=['GET'], type='http')
    def getdelivery(self, saleId=None, **kwargs):
        _logger.info(saleId)
        saleId = str(saleId)
        sale = request.env['sale.order'].sudo().search([('name','=',saleId)])
        if sale.delivery_no and sale.delivery_code:
            if sale.delivery_code == 'shunfeng':
                code = '顺丰快递'
            if sale.delivery_code == 'zhongtong':
                code = '中通快递'
            if sale.delivery_code == 'shentong':
                code = '申通快递'
            if sale.delivery_code == 'yuantong':
                code = '圆通快递'
            if sale.delivery_code == 'yunda':
                code = '韵达快递'
            if sale.delivery_code == 'tiantian':
                code = '天天快递'
            url = "http://www.kuaidi100.com/query?type=%s&postid=%s" % (sale.delivery_code, int(sale.delivery_no))
            response = urllib2.urlopen(url)
            html = response.read().decode('utf-8')
            target = json.loads(html)
            status = target['status']
            if status == '200':
                data = target['data']
                res = []
                for i in range(len(data)):
                    test = {
                        "time":data[i]['time'],
                        "state":data[i]['context']
                    }
                    res.append(test)

                response = request.make_response(
                            headers={
                                "Content-Type": "json"
                            },
                            data=json.dumps({
                                'code':1,
                                'name': 'success',
                                'data':res,
                                'delivery_no':sale.delivery_no,
                                'delivery_code':code
                            })
                        )
            else:
                response = request.make_response(
                            headers={
                                "Content-Type": "json"
                            },
                            data=json.dumps({
                                'code':1111,
                                'name': 'ban-success',
                            })
                        )
        else:
            response = request.make_response(
                            headers={
                                "Content-Type": "json"
                            },
                            data=json.dumps({
                                'code':202,
                                'name': 'fail',
                            })
                        )
        return response